package tom.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

public class HTMLPrintServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String sessionReport = request.getParameter("sessionReport");

		ServletContext servContext = this.getServletConfig()
				.getServletContext();

		JasperPrint jasperPrint = null;

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		try {
			Object obj = servContext.getAttribute(sessionReport);
			if (obj != null) {
				jasperPrint = (JasperPrint) obj;
			}
		} catch (Exception e) {
		}

		if (jasperPrint != null) {
			JRHtmlExporter exporter = new JRHtmlExporter();

			request.getSession().setAttribute(
					ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
					jasperPrint);
			exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,
					"TIS-620");

			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
			exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
					"image?image=");

			try {
				exporter.exportReport();
			} catch (JRException e) {
				e.printStackTrace();
			}

		} else {
			response.setContentType("text/html");
			out.println("<html>");
			out.println("<head>");
			out.println("<title>JasperReports</title>");
			out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../stylesheet.css\" title=\"Style\">");
			out.println("</head>");
			out.println("<body bgcolor=\"white\">");
			out.println("<span class=\"bold\">Empty response.</span>");
			out.println("</body>");
			out.println("</html>");
		}
	}
}
